import 'package:flutter/material.dart';
import 'package:flutter_house_manager/controller/build_controller.dart';
import 'package:flutter_house_manager/pages/Home/index.dart';
import 'package:flutter_house_manager/pages/Mine/index.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:get/get.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  State<TabsPage> createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  final List _tabList = [
    {
      "label": '首页',
      "icon": "assets/tabs/home_default.png",
      "active_icon": "assets/tabs/home_active.png",
    },
    {
      "label": '我的',
      "icon": "assets/tabs/my_default.png",
      "active_icon": "assets/tabs/my_active.png",
    }
  ];
  // 当前选中的索引
  int _currentIndex = 0;

  /// 注册事件
  registerEvent() {
    // 1. 401退出登录处理
    eventBus.on<LogoutEvent>().listen((event) {
      // PromptAction.showSuccess(event.msg);
      // 1.1 清除token
      tokenManager.removeToken();
      // 1.2 跳转登录页面
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  void initState() {
    super.initState();
    tokenManager.init();
    // 2. 注册事件
    registerEvent();
  }

  /// 目的是: 添加和编辑房屋都需要用到这个控制器, 所以把控制器的加入提前到tabs页面
  BuildController buildController = Get.put<BuildController>(BuildController());

  // 返回底部tabs中的item
  List<BottomNavigationBarItem> _getTabsBar() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabList) {
      list.add(
        BottomNavigationBarItem(
          icon: Image.asset(item["icon"], width: 30, height: 30),
          activeIcon: Image.asset(item["active_icon"], width: 30, height: 30),
          label: item["label"],
        ),
      );
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: _currentIndex,
          children: [
            const HomePage(),
            MinePage(currentIndex: _currentIndex),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        items: _getTabsBar(),
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}
